package com.heatup.apt.api.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.plugins.Page;
import com.heatup.apt.api.service.UserAccountConsumeService;
import com.heatup.apt.api.service.UserAccountRechargeService;
import com.heatup.apt.api.service.UserAccountService;
import com.heatup.apt.common.constants.ErrorCodeConstants;
import com.heatup.apt.common.util.JsonTools;
import com.heatup.apt.common.util.RequestTools;
import com.heatup.apt.common.util.ResponseTools;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.user.UserAccountConsume;
import com.heatup.apt.model.user.UserAccountRecharge;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 *  用户储值卡业务控制器
 * @author maxxiang
 *
 */
@Controller
@RequestMapping(value = "/useraccount")
public class UserAccountController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(CouponController.class);
	@Autowired
	UserAccountService userAccountService;
	
	@Autowired
	UserAccountConsumeService userAccountConsumeService;
	
	@Autowired
	UserAccountRechargeService userAccountRechargeService;

	
	
	//兑换 储值卡的码
	//ret: 0表示成功。 1表示已被兑换过。2:表示没有该兑换码。3:该券已失效。4.已领完。5,6,7 9: 其他错误。  请查看定义返回文件
	@ResponseBody
	@RequestMapping(value = "cashcard_change", method={RequestMethod.POST, RequestMethod.GET})
	public String updateCashcardCode(HttpServletRequest request){
		String cashcard_code = RequestTools.RequestString(request, "cashcard_code", "");  //要兑换的券的code: 可能是固定的码 也可能是随机的码
        String callback = RequestTools.RequestString(request, "callback", "");
        Integer onlyQuery = RequestTools.RequestInt(request, "onlyQuery", 0);  //1:只查询。 0: 兑换
        ApiResultModel model = new ApiResultModel();
        String msg = "";
        try {
        	if(isLogined() && !StringUtils.isEmpty(cashcard_code)){
    			Map<String, Object> paramsMap = new HashMap<String, Object>();
    			paramsMap.put("cashcard_code", cashcard_code);  
    			paramsMap.put("user_id", this.getUserInfo().getId());
    			paramsMap.put("onlyQuery", onlyQuery); 
        			
    			model = userAccountService.cashcardChange(paramsMap);
        	}else{
        		model.setRet(ApiResultModel.RET_ERROR);
        	}
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error(ErrorCodeConstants.Code.COUPON_NOT_FOUND.getMessage() + e.getMessage(),e);
            model.setRet(ApiResultModel.RET_ERROR);
            model.setErrorCode(ErrorCodeConstants.Code.COUPON_NOT_FOUND.getCode());	
            model.setMsg(ErrorCodeConstants.Code.COUPON_NOT_FOUND.getMessage());
        }
		model.setLogined(isLogined());
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(model), callback);
	}
	
	
	/**
	 * 获取用户消费记录 :type=1
	 * 获取用户充值记录 :type=2
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/consume_list", method = { RequestMethod.POST, RequestMethod.GET })
	public String getUserAccountConsumeList(HttpServletRequest request,HttpServletResponse response){
		String callback = RequestTools.RequestString(request, "callback", "");
        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<Map<String, Object>>();
        String  type = RequestTools.RequestString(request, "type",null);
        Integer pageNo=RequestTools.RequestInt(request, "pageNo", 0);
    	Integer pageSize=RequestTools.RequestInt(request, "pageSize", 15);
    	Map<String,Object> paramsMap = new HashMap<String,Object>();
    	/**
    	if(pageNo > 0)
            --pageNo;*/
    	paramsMap.put("type",type);
    	/**
    	paramsMap.put("pageIndex",pageNo);
    	paramsMap.put("pageSize",pageSize);*/
    	paramsMap.put("userId",this.getUserId());
    	Map<String,Object> responseMap = new HashMap<>();

    	try {
    		// 交易记录分页查询
        	if("1".equals(type)){
        		Page<UserAccountConsume> userAccountConsumePage = new Page<>(pageNo,pageSize);
        		paramsMap.put("consumeAmt",0);
            	userAccountConsumePage = userAccountConsumeService.queryUserAccountConsumePage(userAccountConsumePage, paramsMap);
            	responseMap.put("userAccountConsumePage",userAccountConsumePage.getRecords());
            	responseMap.put("userAccountConsumeCount",userAccountConsumePage.getTotal());
        	}else{
        		// 充值记录
            	Page<UserAccountRecharge> userAccountRechargePage = new Page<>(pageNo,pageSize);
            	userAccountRechargePage = userAccountRechargeService.queryUserAccountConsumePage(userAccountRechargePage, paramsMap);
            	responseMap.put("userAccountRechargePage",userAccountRechargePage.getRecords());
				responseMap.put("userAccountRechargeCount",userAccountRechargePage.getTotal());
        	}
        	apiResultModel.setMsg("查询成功");
        	apiResultModel.setRet(0);
			apiResultModel.setErrorCode(0);
		} catch (Exception e) {
    		e.printStackTrace();
    		logger.error(e.toString() + e.getCause(),e);
			apiResultModel.setRet(-1);
			apiResultModel.setErrorCode(-1);
			apiResultModel.setMsg("系统错误");
		}
    	
    	apiResultModel.setData(responseMap);
		apiResultModel.setLogined(isLogined());
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}
	
	/**查询用户可以充值的储值卡的面额
	 * RechargeDiscount
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/recharge_discount",method = { RequestMethod.POST, RequestMethod.GET })
	public String getRechargeDiscountList(HttpServletRequest request,HttpServletResponse response){
		String callback = RequestTools.RequestString(request, "callback", "");
        ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>();
        /*Map<String,Object> map = new HashMap<String,Object>();
        map.put("userAccount", userAccountService)*/
        try {
        	apiResultModel = userAccountService.getUserRechargeDiscountList(this.getUserId(),199);
		} catch (Exception e) {
        	e.printStackTrace();
        	logger.error(e.toString() + e.getCause(),e);
			apiResultModel.setData(null);
			apiResultModel.setMsg("系统错误");
			apiResultModel.setLogined(true);
			apiResultModel.setRet(0);
		}
		apiResultModel.setLogined(isLogined());
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}

	/**
	 * 根据批次ID获取兑换码
	 */
	@ResponseBody
	@RequestMapping(value = "query_card_no", method={RequestMethod.POST, RequestMethod.GET})
	public String getCouponCodeByCouponId(HttpServletRequest request){
		Integer cardId = RequestTools.RequestInt(request, "cardId", 0);  //要兑换的券的code: 
        String callback = RequestTools.RequestString(request, "callback", "");
		ApiResultModel model = new ApiResultModel();
		model =userAccountService.queryCardNoByCardId(cardId);
		model.setLogined(isLogined());
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(model), callback);
	}

	
}
